<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { z } from 'zod'
import LoadingContainer from '@/components/common/LoadingContainer.vue'
import message from '@/components/common/message'
import { register, verifyCode } from '@/request/auth'
import AuthInput from './components/AuthInput.vue'
import VerifyCodeInput from './components/VerifyCodeInput.vue'

const router = useRouter()
const account = ref('')
const password = ref('')
const confirmPassword = ref('')
const isLoading = ref(false)
const isVerifyStage = ref(false)
const verifyCodeRef = ref<InstanceType<typeof VerifyCodeInput> | null>(null)
const accountInput = ref<InstanceType<typeof AuthInput> | null>(null)
const passwordInput = ref<InstanceType<typeof AuthInput> | null>(null)
const confirmPasswordInput = ref<InstanceType<typeof AuthInput> | null>(null)

// 只做基础格式校验
const accountSchema = z.string()
  .min(1, '请输入手机号或邮箱')
  .refine(
    (value) => {
      // 手机号或邮箱格式
      const phoneRegex = /^1[3-9]\d{9}$/
      const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
      return phoneRegex.test(value) || emailRegex.test(value)
    },
    { message: '请输入有效的手机号或邮箱地址' },
  )

const passwordSchema = z.string()
  .min(6, '密码至少需要6个字符')
  .max(20, '密码最多20个字符')

const confirmPasswordSchema = computed(() => {
  return z.string()
    .min(6, '确认密码至少需要6个字符')
    .max(20, '确认密码最多20个字符')
    .refine(val => val === password.value, {
      message: '两次输入的密码不一致',
    })
})

const accountValid = ref(false)
const passwordValid = ref(false)
const confirmPasswordValid = ref(false)

function handleValidationError(field: string, _error: string) {
  if (field === 'account')
    accountValid.value = false
  if (field === 'password')
    passwordValid.value = false
  if (field === 'confirmPassword')
    confirmPasswordValid.value = false
}

function handleValidationSuccess(field: string) {
  if (field === 'account')
    accountValid.value = true
  if (field === 'password')
    passwordValid.value = true
  if (field === 'confirmPassword')
    confirmPasswordValid.value = true
}

function validateAllInputs() {
  let isAllValid = true
  if (accountInput.value) {
    const isAccountValid = accountInput.value.forceValidate()
    isAllValid = isAllValid && isAccountValid
  }
  if (passwordInput.value) {
    const isPasswordValid = passwordInput.value.forceValidate()
    isAllValid = isAllValid && isPasswordValid
  }
  if (confirmPasswordInput.value) {
    const isConfirmPasswordValid = confirmPasswordInput.value.forceValidate()
    isAllValid = isAllValid && isConfirmPasswordValid
  }
  return isAllValid
}

async function goToVerifyStage() {
  const isValid = validateAllInputs()
  if (!isValid)
    return
  try {
    isLoading.value = true
    await verifyCode({ data: account.value })
    isVerifyStage.value = true
    message.success('验证码发送成功')
  }
  catch (error: any) {
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

async function handleResendCode() {
  try {
    isLoading.value = true
    await verifyCode({ data: account.value })
    message.success('验证码重新发送成功')
  }
  catch (error: any) {
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

async function handleCodeComplete(code: string) {
  try {
    isLoading.value = true
    await register({
      data: account.value,
      password: password.value,
      verificationCode: code,
    })
    message.success('注册成功，请登录')
    router.push('/auth')
  }
  catch (error: any) {
    message.error(error.message)
    if (verifyCodeRef.value) {
      verifyCodeRef.value.clearCode()
    }
  }
  finally {
    isLoading.value = false
  }
}

function goBackToFirstStep() {
  isVerifyStage.value = false
}
</script>

<template>
  <LoadingContainer :loading="isLoading">
    <div v-if="!isVerifyStage" class="register-container">
      <div class="register-header">
        <h1>注册</h1>
        <p>创建您的账号</p>
      </div>
      <div class="register-inputs">
        <AuthInput
          ref="accountInput" v-model="account" type="phone-email" placeholder="请输入手机号或邮箱" :schema="accountSchema"
          @validation-error="(error) => handleValidationError('account', error)"
          @validation-success="() => handleValidationSuccess('account')"
        />
        <AuthInput
          ref="passwordInput" v-model="password" type="password" placeholder="请输入密码" :schema="passwordSchema"
          @validation-error="(error) => handleValidationError('password', error)"
          @validation-success="() => handleValidationSuccess('password')"
        />
        <AuthInput
          ref="confirmPasswordInput" v-model="confirmPassword" type="password" placeholder="请确认密码" :schema="confirmPasswordSchema"
          @validation-error="(error) => handleValidationError('confirmPassword', error)"
          @validation-success="() => handleValidationSuccess('confirmPassword')"
        />
      </div>
      <button class="next-step-button" :disabled="isLoading" @click="goToVerifyStage">
        {{ isLoading ? '处理中...' : '下一步' }}
      </button>
      <div class="login-link">
        已有账号? <a @click="router.push('/auth')">立即登录</a>
      </div>
    </div>
    <div v-else class="verify-container">
      <VerifyCodeInput
        ref="verifyCodeRef"
        :phone-number="account"
        :disabled="isLoading"
        @complete="handleCodeComplete"
        @resend="handleResendCode"
      >
        <template #back-button>
          <span class="back-icon" @click="goBackToFirstStep">&lt;</span>
        </template>
      </VerifyCodeInput>
    </div>
  </LoadingContainer>
</template>

<style scoped>
.register-header {
  text-align: center;
  margin-bottom: 32px;
}

.register-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.register-header p {
  font-size: 16px;
  color: #666;
}

.register-inputs {
  margin-bottom: 24px;
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 16px;
  text-align: center;
}

.next-step-button {
  width: 100%;
  height: 50px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 24px;
}

.next-step-button:hover {
  background-color: #40a9ff;
}

.next-step-button:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}

.back-icon {
  font-size: 24px;
  cursor: pointer;
}
</style>
